package com.zhudao.crawler.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.zhudao.crawler.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CrawlerGangJiService {

    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    private static final Logger logger = LoggerFactory.getLogger(CrawlerGangJiService.class);

    /**
     * 个人房源
     *
     * @throws IOException
     * @throws InterruptedException
     */
    @Async
    public void gangji(String identity, String url) throws IOException, InterruptedException {
        while (true) {
            for (int i = 1; i < 438; i++) {
                String body = HttpUtil.get(url + i);
                Thread.sleep(4000);
                JSONPObject jsonpObject = JSON.parseObject(body, JSONPObject.class);
                List<Object> json = jsonpObject.getParameters();
                JSONObject object = (JSONObject) json.get(0);
                JSONArray data = object.getJSONArray("data");
                logger.info("第{},总条数:{}", i, data.size());
                for (int y = 0; y < data.size(); y++) {
                    JSONObject jsonObject = data.getJSONObject(y);
                    String person = jsonObject.getString("person");
                    String phone = jsonObject.getString("phone");
                    String price = jsonObject.getString("price");
                    try {
                        Map<String, Object> map1 = jdbcTemplate.queryForMap("SELECT COUNT(1) as count from userInfo where  phone=?", phone);
                        Integer count = Integer.valueOf(map1.get("count").toString());
                        if (count == 0) {
                            logger.info("插入赶集{}的数据，电话号码:{}", identity, phone);
                            jdbcTemplate.update("INSERT into userInfo VALUE (?,?,?,?,?,?,?)", phone, person, identity, "上海", price, "赶集", new Date());
                        } else {
                            logger.info("赶集手机号已存在:{}", phone);
                        }
                    } catch (Exception ex) {
                        logger.info("异常了", ex);
                    }
                }
            }
        }
    }


}


